
from flask import Flask, render_template, jsonify, request
import os
import datetime

app = Flask(__name__)

@app.route('/')
def index():
    """首页，显示所有文章列表"""
    return render_template('index.html')

@app.route('/view/<filename>')
def view_article(filename):
    """查看文章页面"""
    return render_template('view.html', filename=filename)

@app.route('/edit/<filename>')
def edit_article(filename):
    """编辑文章页面"""
    return render_template('edit.html', filename=filename)

@app.route('/api/get_markdown', methods=['GET'])
def get_markdown():
    # 获取文件名参数
    filename = request.args.get('filename', 'kk.md')
    # 安全检查，防止目录遍历攻击
    if '..' in filename or '/' in filename or '\\' in filename:
        return jsonify({'error': '无效的文件名'}), 400

    file_path = os.path.join(os.path.dirname(__file__), filename)

    try:
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()

            # 获取文件修改时间
            mod_time = os.path.getmtime(file_path)
            mod_time_str = datetime.datetime.fromtimestamp(mod_time).strftime('%Y-%m-%d %H:%M:%S')

            return jsonify({
                'content': content, 
                'modified': mod_time_str
            })
        else:
            return jsonify({'error': '文件不存在'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/save_markdown', methods=['POST'])
def save_markdown():
    data = request.json
    filename = data.get('filename', '')
    content = data.get('content', '')

    if not filename:
        return jsonify({'error': '文件名不能为空'}), 400

    # 安全检查，防止目录遍历攻击
    if '..' in filename or '/' in filename or '\\' in filename:
        return jsonify({'error': '无效的文件名'}), 400

    file_path = os.path.join(os.path.dirname(__file__), filename)

    try:
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content)
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/list_articles')
def list_articles():
    """列出所有Markdown文章"""
    try:
        articles = []
        base_dir = os.path.dirname(__file__)

        # 遍历目录中的所有.md文件
        for filename in os.listdir(base_dir):
            if filename.endswith('.md'):
                file_path = os.path.join(base_dir, filename)
                mod_time = os.path.getmtime(file_path)
                mod_time_str = datetime.datetime.fromtimestamp(mod_time).strftime('%Y-%m-%d %H:%M:%S')

                # 读取文件获取标题
                title = filename.replace('.md', '')
                try:
                    with open(file_path, 'r', encoding='utf-8') as file:
                        first_line = file.readline().strip()
                        if first_line.startswith('# '):
                            title = first_line[2:].strip()
                except:
                    pass

                articles.append({
                    'filename': filename,
                    'title': title,
                    'modified': mod_time_str
                })

        # 按修改时间排序，最新的在前
        articles.sort(key=lambda x: x['modified'], reverse=True)

        return jsonify(articles)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)

